package mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

public class MyBatisDemo {

    private static final Logger log = LoggerFactory.getLogger(MyBatisDemo.class);

    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {

        log.info("开始执行！！！！！！！！！！！！！！！！！！！");
        selectList();
    }

    private static void selectNameById(){
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            User u = mapper.selectNameById(1);
            log.info("查询结果： [{}]", u);
        }
    }

    private static void update(){
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            int num = mapper.update(new User(1,"Jack"));
            log.info("更新数量： [{}]", num);
        }
    }

    private static void selectList(){
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            List<User> users = mapper.selectList();
            for (User user : users) {
                log.info("查询结果： [{}]", user);
            }
        }
    }





    private static SqlSession openSession(){
        //事务自动提交
        return sqlSessionFactory.openSession(true);
    }
}
